# -*- coding: utf-8 -*-
import re
from .infrastructure import Record
from multiprocessing.pool import ThreadPool as Pool
from multiprocessing import cpu_count
from functools import partial


class CPCATransformer:

    # 可以传入用户自定义区县map，因为原始数据区县map有很多key重复
    def __init__(self, u_map={}):
        self.umap = u_map
        self.cpuCount = cpu_count()


    def transform(self, data, index=[], cut=True, lookahead=8):
        from .infrastructure import SuperMap
        SuperMap.rep_area_set = set()
        import pandas as pd
        if isinstance(data, pd.Series):
            data = data.astype(str)

        lines = []
        for line in data:
            lines.append(self.__del_data(line))

        record = Record()
        pool = Pool()
        # para = partial(record.run, self.umap, cut, lookahead)
        # poolRet = pool.map_async(para, lines)
        # ret = poolRet.get(timeout=60)

        para = partial(record.run, self.umap, cut, lookahead)
        ret = pool.map(para, lines)

        pool.close()
        pool.join()

        import pandas as pd
        result = pd.concat(ret, ignore_index=True)

        # 设置用户自定义的index
        if len(index) == 0:
            return result
        if len(index) != len(data):
            from .exceptions import CPCAException
            raise CPCAException("index参数的长度应该与data一致")
        result['index'] = index
        return result.set_index('index')

    # 数据过滤
    def __del_data(self, line):

        line = re.sub(r'（\S+）', "", line)
        line = re.sub(r'\(\S+\)', "", line)
        line = re.sub(r'\[\S+\]', "", line)
        line = re.sub(r'[\[\]\(\)（）{}~]', "", line)
        return line
